#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

//互斥锁
//临界资源


//全局定义
FILE* pf;        //文件指针
pthread_mutex_t pfmutex = PTHREAD_MUTEX_INITIALIZER;  //写文件锁


//线程1
void* func( void* agr)
{
	pthread_detach(pthread_self());		//线程分离
	printf("线程创建成功\n");
	char str[] = "hello linux\n";

	while(1)
	{
		pthread_mutex_lock(&pfmutex);		//获得锁
		fputs(str, pf);
		pthread_mutex_unlock(&pfmutex);    //解锁
		sleep(1);
	}
	pthread_exit(0);

}


//线程2
void* func2( void* agr)
{
	pthread_detach(pthread_self());	  //线程分离
	printf("线程2创建成功\n");

	//写文件
	char str1[] = "xiao yang\n";
	while(1)
	{
		pthread_mutex_lock(&pfmutex);   //获得锁
		fputs(str1, pf);
		pthread_mutex_unlock(&pfmutex);	//解锁
		sleep(1);
	}

	pthread_exit(0);

}




int main()
{
	pthread_t tid;
	pthread_t tid2;

	//打开文件
	pf = fopen("1.data", "w+");
	if(pf == NULL)
	{

		perror("fopen");
		return -1;
	}

	//创建线程
	pthread_create(&tid, NULL, func, NULL);
	pthread_create(&tid2, NULL, func2, NULL);

	//阻止主线程结束
	sleep(3);

	fclose(pf);		//关闭文件
	printf("文件已关闭\n");

	return 0;
}
